package logic

import (
	"context"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"math/rand"
	"video-guard/models/cache"
	"video-guard/models/mysql"
	"video-guard/pkg"
	"video-guard/videorpc/internal/svc"
	"video-guard/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *videorpc.RegisterRequest) (*videorpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.UserInfo

	err := user.FindUserByMobile(mysql.DB, in.Mobile)
	if err != nil {
		return nil, errors.New("查询失败")
	}

	if user.ID != 0 {
		return nil, errors.New("该手机号已注册，可直接登录")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()

	if result != in.SmsCode {
		return nil, errors.New("验证码错误")
	}

	user = mysql.UserInfo{
		Model:      gorm.Model{},
		PhoneNum:   in.Mobile,
		Pwd:        pkg.Md5(in.Password),
		NickName:   fmt.Sprintf("用户%d", rand.Intn(900)+100),
		AvatarLink: "http://t4ka9jbmh.hn-bkt.clouddn.com/b_1f05c0d38d690c0f02ff1ea12fbf5d35.jpg",
	}

	err = user.UserAdd(mysql.DB)
	if err != nil {
		return nil, errors.New("添加失败")
	}

	return &videorpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
